package com.itheima.health.controller.admin;

import com.itheima.health.common.MessageConst;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.result.PageResult;
import com.itheima.health.result.QueryPageBean;
import com.itheima.health.result.Result;
import com.itheima.health.service.SetmealService;
import com.itheima.health.util.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {


    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private SetmealService setmealService;

    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){

        try {
            setmealService.add(setmeal,checkgroupIds);
        } catch (Exception e) {
            return new Result(false,MessageConst.ADD_SETMEAL_SUCCESS);
        }

        return new Result(true,MessageConst.ADD_SETMEAL_FAIL);
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile){

        try {
            String originalFilename = imgFile.getOriginalFilename();

            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            String objectName=UUID.randomUUID().toString()+ extension;
            String filePath = aliOssUtil.upload(imgFile.getBytes(), objectName);

            return new Result(true, MessageConst.ACTION_SUCCESS,filePath);
        } catch (IOException e) {
            return new Result(false,MessageConst.ACTION_FAIL);
        }

    }

    @GetMapping("/findPage")
    public Result page(QueryPageBean queryPageBean){
        PageResult pageResult=setmealService.pageQuery(queryPageBean);
        return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,pageResult);
    }


}
